<template>
<div>
  <!-- 面包屑 -->
  <el-breadcrumb separator="/">
  <el-breadcrumb-item :to="{ path: '/welcome' }"><span @click="clearPath" >首页</span></el-breadcrumb-item>
  <!-- <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item> -->
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片区域 -->
<el-card >
  <!-- 搜索 -->
  <el-row :gutter="20">
    <el-col :span="8">
       <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
      </el-input>
     </el-col>
     <el-col :span="4">
      <el-button type="primary" @click="addUsersBtn">添加用户</el-button>
    </el-col>
  </el-row>
  <!-- 新增用户弹出框 -->
  <el-dialog
  title="新增用户"
  :visible.sync="addUserDialog"
  width="50%" @close="addUserDialogCl">
  <el-form :model="searchUsersList" :rules="userRules" ref="ruleFormRef" label-width="70px" >
          <!-- ref在普通标签获取dom对象 -->
          <!-- 在组件上 则获取组件的实例 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="searchUsersList.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="searchUsersList.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="searchUsersList.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="searchUsersList.mobile"></el-input>
          </el-form-item>
          </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addUserDialog = false">取 消</el-button>
    <el-button type="primary" @click="addUserForm">确 定</el-button>
  </span>
</el-dialog>
  <!-- 表格 -->
  <el-table
    :data="userList"
    border
    style="width: 100%" stripe>
    <el-table-column prop="id" label="#" type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
        label="状态">
        <template slot-scope="data">
          <el-switch
            v-model="data.row.mg_state"
            active-color="#66b1ff"
            inactive-color="#e9edf1" @change="changeSwitch(data.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="操作">
          <template slot-scope="data">
          <div class="bt">
            <el-button type="primary" size="mini"  icon="el-icon-edit"  @click="showEidetForm(data.row.id)"></el-button>
            <el-button type="danger"   size="mini"  icon="el-icon-delete"  @click="del(data.row.id)"></el-button>
            <el-tooltip  effect="dark" content="设置" placement="top">
              <el-button type="warning"  size="mini" icon="el-icon-setting" @click="set(data.row.id)"></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
  </el-table>
  <!-- 修改用户弹出框 -->
   <el-dialog
        title="编辑用户"
        :visible.sync="setDialogVisible"
        width="50%">
        <!-- 内容主体区 是一个默认插槽-->
        <el-form :model="setUserForm" :rules="userRules" ref="ruleFormRef" label-width="70px" >
          <!-- ref在普通标签获取dom对象 -->
          <!-- 在组件上 则获取组件的实例 -->
          <el-form-item label="用户名" >
            <el-input v-model="setUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="setUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="setUserForm.mobile"></el-input>
          </el-form-item>
          </el-form>
        <!-- 底部区域 为具名插插-->
      <span slot="footer" class="dialog-footer">
      <el-button @click="setDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setUsers">确 定</el-button>
    </span>
    </el-dialog>
<!-- 修改用户角色 对话框 -->
     <el-dialog
        title="提示"
        :visible.sync="UserDialogVisible"
        width="50%" @close="UserDialogClose" ref="UserDialogRef">
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前用户角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="userRoles" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :value="item.id"
              :label="item.roleName"
              :v-model="userRoles">
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="UserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="selectSure">确 定</el-button>
        </span>
      </el-dialog>
  <!-- 分页按钮 -->
  <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total" background >
    </el-pagination>
  </div>
</el-card>
</div>
</template>

<script>
const aa = 'sss'
console.log(aa)
export default {
  props: ['fName', 'meName'],
  data () {
    var checkmobile = (rule, value, callback) => {
      // console.log(rule) 校验规则对象
      const regmobile = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (!regmobile.test(value)) return callback(new Error('手机号格式错误'))
      callback()
    }
    var checkEmail = (rule, value, callback) => {
      const regEmaill = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!regEmaill.test(value)) return callback(new Error('邮箱格式错误'))
      callback()
    }
    return {
      userList: [],
      total: 0,
      params: {
        query: '',
        pagenum: 1, // 当前页码
        pagesize: 2 // 每页显示条数
      },
      addUserDialog: false,
      setDialogVisible: false,
      searchUsersList: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      setUserForm: {},
      UserDialogVisible: false,
      userInfo: {}, // 点击显示用户信息
      userRoles: 0, // 当前用户的角色信息id
      rolesList: '' // 所有角色
    }
  },
  methods: {
    clearPath () {
      sessionStorage.removeItem('path')
      this.$router.go(0)
    },
    async getUserList () { // 获取用户信息
      const { data: res } = await this.$http.get('users', { params: this.params })
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.userList = res.data.users
      this.total = res.data.total
      console.log(1)
    },
    handleSizeChange (val) { // 每页显示的数量发生变化会触发
      this.params.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) { // 显示的页码变化会触发
      this.params.pagenum = val
      this.getUserList()
    },
    async changeSwitch (data) { // 修改用户状态
      const { data: res } = await this.$http.put('users/' + data.id + '/state/' + data.mg_state)
      if (res.meta.status !== 200) {
        data.mg_state = !data.mg_state
        return this.$notify.error({ title: '错误', message: res.meta.msg })
      }
      this.$notify({ title: '成功', message: res.meta.msg, type: 'success' })
    },
    search () { // 搜索按钮
      this.getUserList()
    },
    addUsersBtn () { // 点击弹出添加用户对话框
      this.addUserDialog = true
    },
    addUserForm () { // 添加用户确认按钮
      this.$refs.ruleFormRef.validate(boolean => {
        if (!boolean) return this.$message.error('格式错误')
        this.addUserFormUrl()
      })
    },
    async addUserFormUrl () { // 发出添加用户请求
      const { data: res } = await this.$http.post('users', this.searchUsersList)
      this.addUserDialog = false
      if (res.meta.status !== 201) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.$notify({ title: '成功', message: res.meta.msg, type: 'success' })
      this.params.pagenum = Math.ceil(this.total + 1 / this.params.pagesize)
      this.getUserList()
    },
    addUserDialogCl () {
      this.$refs.ruleFormRef.resetFields()
    },
    setUsers () { // 修改用户按钮
      this.$refs.ruleFormRef.validate(boolean => {
        if (!boolean) return this.$message.error('格式错误')
        this.addEidetForm()
        this.setDialogVisible = false
      })
    },
    async showEidetForm (id) { // 修改用户弹框
      this.setDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.setUserForm = res.data
    },
    async addEidetForm () { // 修改用户请求
      const { data: res } = await this.$http.put('users/' + this.setUserForm.id, { email: this.setUserForm.email, mobile: this.setUserForm.mobile })
      if (res.meta.status !== 200) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.$notify({ title: '成功', message: res.meta.msg, type: 'success' })
      this.params.pagenum = Math.ceil(this.total + 1 / this.params.pagesize)
      this.getUserList()
    },
    async del (id) { // 删除用户弹框
      const config = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).catch(res => res)
      if (config !== 'confirm') return false
      this.delUrl(id)
    },
    async delUrl (id) { // 删除用户信息请求地址
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.$notify({ title: '成功', message: res.meta.msg, type: 'success' })
      if (this.userList.length === 1) {
        this.params.pagenum = this.params.pagenum === 1 ? this.params.pagenum : (this.params.pagenum - 1)
      }
      this.getUserList()
    },
    async set (id) { // 修改用户角色
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.userInfo = res.data
      const { data: ress } = await this.$http.get('roles') // 获取全部角色信息
      if (ress.meta.status !== 200) return this.open1('删除用户失败', 'warning')
      this.rolesList = ress.data
      console.log(this.rolesList)
      this.UserDialogVisible = true
    },
    UserDialogClose () {
      this.userRoles = ''
      this.userInfo = ''
    },
    async selectSure () { // 修改用户角色确认按钮
      console.log(this.userRoles)
      const { data: res } = await this.$http.put('users/' + this.userInfo.id + '/role', { rid: this.userRoles }) // 获取全部角色信息
      if (res.meta.status !== 200) return this.$notify.error({ title: '错误', message: res.meta.msg })
      this.getUserList()
      this.UserDialogVisible = false
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb{
  font-size: 12px;
  margin-bottom: 20px;
}
.bt {
display: flex;
}
.block {
  margin-top: 10px;
}
</style>
